from django.contrib.auth.hashers import make_password

from apps.system.models import Region, WorkflowStep, Workflow, OperationRecord, Organization
from extensions.common.base import *
from extensions.serializers import *
from extensions.exceptions import *
from apps.system.models import *
# from apps.goods.models import *


class OperationRecordSerializer(BaseSerializer):
    name = CharField(source='user.name', read_only=True, label='姓名')
    class Meta:
        model = OperationRecord
        fields = "__all__"


class LoginLogSerializer(BaseSerializer):
    company_name = CharField(source='user.company.name', read_only=True, label='公司')
    name = CharField(source='user.name', read_only=True, label='公司')
    class Meta:
        model = LoginLog
        fields = "__all__"


class JobsSerializer(BaseSerializer):

    class Meta:
        model = Job
        read_only_fields = ['id',]
        fields = ['name','index',*read_only_fields]

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class DictsSerializer(BaseSerializer):

    class Dict_itemsSerializer(BaseSerializer):

        class Meta:
            model = Dict_item
            fields = ['id', 'name','description']

    # sex_display = CharField(source='get_sex_display', read_only=True, label='性别')
    dict_items = Dict_itemsSerializer(source='dict_item', many=True, read_only=True, label='字典项')

    class Meta:
        model = Dict
        read_only_fields = ['id','dict_items']
        fields = ['name','code','description',*read_only_fields]
        extra_kwargs = {'dict_item': {'required': False}}

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class RegionsSerializer(BaseSerializer):

    class Meta:
        model = Region
        read_only_fields = ['id']
        fields = ['region_name','region_parent_id','region_short_name','index','region_level',*read_only_fields]



class PermissionGroupSerializer(BaseSerializer):

    class PermissionItemSerializer(BaseSerializer):

        class Meta:
            model = Permission
            fields = ['id', 'name', 'code']

    permission_items = PermissionItemSerializer(source='permissions', many=True, label='权限')

    class Meta:
        model = PermissionGroup
        fields = ['id', 'name', 'permission_items']


class RoleSerializer(BaseSerializer):

    class Meta:
        model = Role
        read_only_fields = ['id']
        fields = ['name', 'remark', 'permissions', *read_only_fields]

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class OrganizationSerializer(BaseSerializer):
    children = SerializerMethodField(read_only=True, label='子组织')

    class Meta:
        model = Organization
        fields = ('id', 'name', 'coding_abbreviation', 'organization_level', 'index', 'type', 'parent','children')

    def get_children(self, obj):
        """获取子组织"""
        if obj.children.all().exists():
            return OrganizationSerializer(obj.children.order_by('index'), many=True).data
        return None

class UserSerializer(BaseSerializer):

    class RoleItemSerializer(BaseSerializer):

        class Meta:
            model = Role
            fields = ['id', 'name']

    # sex_display = CharField(source='get_sex_display', read_only=True, label='性别')
    role_items = RoleItemSerializer(source='roles', many=True, read_only=True, label='角色Item')


    class Meta:
        model = User
        read_only_fields = ['id', 'is_manager', 'role_items', 'permissions', 'create_time']
        fields = ['username', 'name', 'phone', 'email', 'roles', 'job', 'is_active',
                  *read_only_fields]

    def validate_username(self, value):
        self.validate_unique({'username': value}, message=f'用户名[{value}]已存在')
        return value

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value

    def validate_roles(self, instances):
        instances = self.validate_foreign_key_set(Role, instances, message='角色不存在')
        return instances

    def create(self, validated_data):
        validated_data['password'] = make_password(validated_data['username'])
        return super().create(validated_data)

    def save(self, **kwargs):
        permissions = []
        if roles := self.validated_data.get('roles'):
            permissions = {permission.code for role in roles.prefetch_related('permissions').all()
                           for permission in role.permissions.all()}

        kwargs['permissions'] = list(permissions)
        return super().save(**kwargs)


class WorkflowSerializer(BaseSerializer):
    class WorkflowStepSerializer(BaseSerializer):
        approval_permission_code = CharField(source='approval_permission.code', read_only=True, label='审批权限')
        class Meta:
            model = WorkflowStep
            fields = ['id', 'name', 'approval_permission_code', 'step_number', 'is_final_step']

    steps = WorkflowStepSerializer(many=True, read_only=True)

    class Meta:
        model = Workflow
        fields = ['id', 'name', 'steps']


__all__ = [
    'PermissionGroupSerializer',
    'RoleSerializer', 'UserSerializer',
    'JobsSerializer',
    'DictsSerializer',
    'WorkflowSerializer',
]
